﻿using HelpWeb.WeiXin;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using XQ.SP.Model;

namespace XM.Controllers
{
    public class UserController : Controller
    {
        //后台页面1
        public ActionResult UIA()
        {
            return View();
        }

        //后台页面2
        public ActionResult UIA2()
        {
            ViewBag.UserName = Session["Name"];
            return View();
        }

        /// <summary>
        /// 登陆
        /// </summary>
        /// <param name="account"></param>
        /// <returns></returns>
        public ActionResult LoginUIA()
        {
            UsersItem item = new UsersItem();
            return View(item);
        }

        [HttpPost]
        public ActionResult LoginUIA(UsersItem model)
        {
            //if (model.UserName == "admin123" & model.UserPassword == "admin123")
            //{
            //    Session["Limit"] = "admin123";
            //    Session["Admin"] = "1";  // 表示管理员
            //    return RedirectToAction("UIA2", "user", new { u = "/users/List", name = "用户管理" });
            //}
            XQ.SP.BllServices.UserInfoBLL bll = new XQ.SP.BllServices.UserInfoBLL();
            var m = bll.GetModelWhereStr(" UserName='" + model.UserName + "' and Pwd='" + model.UserPassword + "' ");
            if (m!=null)
            {
                //Session["Limit"] = "admin123";
                //Session["Admin"] = "0";  // 表示非管理员
                Session["Users"] = m;
                Session["Name"] = model.UserName;
                //确认用户登录 写入cookies
                XQ.Common.Cookies.CreateTicket(true, m.UserName + "[,]" + m.Id + "[,]" + 0 + "[,]" + "教育" + "[,]", "member");
                return RedirectToAction("UIA2", "User");
            }
            return View(model);
        }

        public ActionResult My()
        {
            return View();
        }


        /// <summary>
        /// 我的微信二维码（页面）
        /// </summary>
        /// <returns></returns>
        public ActionResult MyNo()
        {
            HelpWeb.WeiXin.WeiXinHelper wxHper = new HelpWeb.WeiXin.WeiXinHelper();
            string ts = wxHper.Get_tokenOnly();
            string tempStr1 = wxHper.CreateTicket(ts);
            @ViewBag.ImageQr = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=" + tempStr1;

            return View();
        }



        public ActionResult WeiXinLogin()
        {
            string code = "";
            if (Request.QueryString["code"] != null && Request.QueryString["code"] != "")
            {
                HelpWeb.WeiXin.WeiXinHelper wxHper = new WeiXinHelper();
                Session["WXOI"] = "WP";
                //获取微信回传的code
                code = Request.QueryString["code"].ToString();
                OAuth_Token Model = wxHper.Get_token(code);  //获取token
                string op = Model.openid.Trim();
                //HandleException("Code:" + code + "____" + op);
                //OAuth_Token Model = Get_token(code);  //获取token
                //HandleException(Model.access_token + "----" + Model.openid);

                OAuthUser OAuthUser_Model = wxHper.Get_UserInfo(Model.access_token, Model.openid);
                string nameStrW = OAuthUser_Model.nickname;
                if (string.IsNullOrEmpty(op))
                {
                    throw new Exception("OpenId为空");
                    Session["WXOI"] = "WP";
                }
                else
                {
                    HandleException(OAuthUser_Model.nickname + "-----------" + Model.openid);
                    Session["WXOI"] = "WaP";
                    //wxHper.HandleException("Code:" + code + "____Op:" + op);
                    #region
                    XQ.SP.BllServices.UsersBLL bllUserInfo = new XQ.SP.BllServices.UsersBLL();
                    var itemCheck = bllUserInfo.GetModelWhereStr(" WeiXin='" + op + "' ");
                    if (itemCheck != null)
                    {
                        //if (itemCheck.UserName == op)
                        //{
                        itemCheck.UserName = nameStrW;
                        bllUserInfo.Update(itemCheck);
                        //}

                        var modelU = bllUserInfo.GetModel(itemCheck.Id);
                        modelU.UserName = nameStrW;
                        bllUserInfo.Update(modelU);
                        #region
                        Session["Users"] = modelU;
                        //确认用户登录 写入cookies
                        XQ.Common.Cookies.CreateTicket(true, modelU.UserName + "[,]" + modelU.Id + "[,]22[,]33[,]", "member");

                        #region
                        if (Session["BackUrl"] != null)
                        {
                            Redirect(Session["BackUrl"].ToString());
                            return Redirect(Session["BackUrl"].ToString());
                        }

                        HttpCookie cookie = Request.Cookies["BackUrl"];
                        if (cookie != null)
                        {
                            return Redirect(cookie.Value);
                        }
                        if (!string.IsNullOrEmpty(op))
                        {
                            return RedirectToAction("IndexW", "Users");
                        }
                        else
                        {
                            return RedirectToAction("IndexW", "Home");
                        }
                        #endregion
                        #endregion
                    }
                    else
                    {
                        //var itemU = blluser.GetModelWhereStr(" UserName='" + nameStrW + "' ");
                        //if (itemU != null)
                        //{
                        //    Session["Users"] = itemU;
                        //    //确认用户登录 写入cookies
                        //    XQ.Common.Cookies.CreateTicket(true, itemU.UserName + "[,]" + itemU.UsersID + "[,]" + UsersInfo.GetXiaoQuIDC() + "[,]" + UsersInfo.GetXiaoQuNameC() + "[,]", "member");
                        //}
                        //else
                        //{
                        //var bllUserInfo = new XQ.SP.BllServices.UsersBLL();
                        var modelu = new XQ.SP.Model.UsersItem();
                        modelu.UserName = nameStrW;
                        modelu.UserPassword = "123456";
                        //modelu.XiaoQuID = UsersInfo.GetXiaoQuID();
                        //添加登录信息
                        //int usersId = blluser.RegUsers(modelu);
                        //modelu = blluser.GetModel(usersId);
                        ////详细资料有则添加
                        ////new XQ.BLL.Users.UsersInfo().GetModelWhereUsersID(usersId, op);
                        //var itemInfo = blluserInfo.GetModelWhereUsersID(usersId, op);
                        modelu.WeiXin = op;
                        modelu.UserName = modelu.UserName;
                        modelu.RealName = modelu.RealName;
                        modelu.Birthday = DateTime.Now;
                        modelu.Created = DateTime.Now;
                        modelu.Modified = DateTime.Now;
                        modelu.UpLoginTime = DateTime.Now;
                        modelu.CreateTime = DateTime.Now;

                        XQ.SP.BllServices.UsersBLL bllu = new XQ.SP.BllServices.UsersBLL();
                        bllu.Add(modelu);
                        //blluserInfo.Add(modelu);

                        Session["Users"] = modelu;
                        //确认用户登录 写入cookies
                        XQ.Common.Cookies.CreateTicket(true, modelu.UserName + "[,]" + modelu.Id + "[,]22[,]33[,]", "member");
                        //}

                    }
                    #endregion
                    if (Session["BackUrl"] != null)
                    {
                        Redirect(Session["BackUrl"].ToString());
                        return Redirect(Session["BackUrl"].ToString());
                    }


                    HttpCookie cookie1 = Request.Cookies["BackUrl"];
                    if (cookie1 != null)
                    {
                        return Redirect(cookie1.Value);
                    }
                    if (!string.IsNullOrEmpty(op))
                    {
                        return RedirectToAction("My", "User");
                    }
                    else
                    {
                        return RedirectToAction("My", "User");
                    }
                }
            }
            else
            {
                if (Session["WXOI"] == null)
                {
                    string appid = "wx3c8f36a0d499a44e";
                    //不弹出授权页面
                    Response.Redirect("https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + appid + "&redirect_uri=http%3a%2f%2fweixin.58xiao.com%2fUsers%2fWeiXinLogin%3freurl%3dhttp%3a%2f%2fweixin.58xiao.com%2fUsers%2fIndexW&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect");
                    return Redirect("https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + appid + "&redirect_uri=http%3a%2f%2fweixin.58xiao.com%2fUsers%2fWeiXinLogin%3freurl%3dhttp%3a%2f%2fweixin.58xiao.com%2fUsers%2fIndexW&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect");
                    Session["WXOI"] = "WP";
                }
            }

            if (Session["BackUrl"] != null)
            {
                Redirect(Session["BackUrl"].ToString());
                return Redirect(Session["BackUrl"].ToString());
            }
            return RedirectToAction("My", "User");
            //return RedirectToAction("IndexW", "Home");
        }

        public void HandleException(string ex)
        {
            //string pathStr = System.Environment.CurrentDirectory;
            string pathStr = HttpRuntime.AppDomainAppPath.ToString();
            //pathStr += "\\LogWin\\" + DateTime.Now.Year + "\\" + DateTime.Now.Month + "\\" + DateTime.Now.Day + "\\";
            pathStr += "\\LogWin\\" + DateTime.Now.Year + "\\";
            if (!System.IO.Directory.Exists(pathStr))
            {
                System.IO.Directory.CreateDirectory(pathStr);
            }
            DateTime now = DateTime.Now;
            string logpath = string.Format(@"Error_{0}{1}{2}{3}.log", now.Year, now.Month, now.Day, now.Hour);
            logpath = pathStr + logpath;

            FileInfo finfo = new FileInfo(logpath);
            if (!finfo.Exists)
            {
                FileStream fs;
                fs = System.IO.File.Create(logpath);
                fs.Close();
                finfo = new FileInfo(logpath);
            }
            using (FileStream fs = finfo.OpenWrite())
            {
                /**/
                ///根据上面创建的文件流创建写数据流
                StreamWriter w = new StreamWriter(fs);
                /**/
                ///设置写数据流的起始位置为文件流的末尾
                w.BaseStream.Seek(0, SeekOrigin.End);
                /**/
                ///写入“Log Entry : ”
                w.Write("\n\rLog Entry : ");
                /**/
                ///写入当前系统时间并换行
                w.Write("{0} {1} \r\n", DateTime.Now.ToLongTimeString(),
                    DateTime.Now.ToLongDateString());
                /**/
                ///写入日志内容并换行
                w.Write("------------------------------------\r\n");
                w.Write("------------------------------------\r\n");
                w.Write("------------------------------------\r\n");
                w.Write(ex.ToString() + "\r\n");
                /**/
                ///写入------------------------------------“并换行
                w.Write("------------------------------------\r\n");
                /**/
                ///清空缓冲区内容，并把缓冲区内容写入基础流
                w.Flush();
                /**/
                ///关闭写数据流
                w.Close();
            }
        }
    }
}
